<?php

namespace app\common\controller;

use think\facade\Env;

/**
 * 抖音登录
 */
class ApiByteLogin
{

  /**
   * 初始化方法
   */
  protected function initialize() {}


  public function login($code = '')
  {
    // 抖音开放平台的API地址
    $apiUrl = "https://developer.toutiao.com/api/apps/v2/jscode2session";
    // 你的小程序AppID和AppSecret
    $appId = Env::get('BYTE.BYTE_APPID');
    $appSecret = Env::get('BYTE.BYTE_SECRET');
    // 前端传递的code
    // 请求参数
    $params = [
      'appid' => $appId,
      'secret' => $appSecret,
      'code' => $code,
    ];
    // 发送HTTP请求
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'Content-Type: application/json',
    ]);
    $response = curl_exec($ch);
    if ($response === false) {
      file_put_contents('curl_error.log', "CURL错误: " . curl_error($ch) . "\n", FILE_APPEND);
    }
    curl_close($ch);
    // 解析响应
    $responseData = json_decode($response, true);    
    if (isset($responseData['data']) && $responseData['err_no'] == 0) {
      $sessionKey = $responseData['data']['session_key'];
      $openId = $responseData['data']['openid'];
      $unionid = $responseData['data']['unionid'];
       
      return [
        'status' => 'success',
        'session_key' => $sessionKey,
        'openid' => $openId,
        'unionid' =>$unionid
      ];
    } else {
      return [
        'status' => 'error',
        'message' => 'Failed to get session key and openid.',
      ];
    }
  }

  // // 示例调用
  // $encryptedData = $_POST['encryptedData'];
  // $iv = $_POST['iv'];
  // $userInfo = decryptData($encryptedData, $iv, $sessionKey);
  //解密用户信息
  public function decryptData($encryptedData, $iv, $sessionKey)
  {
    $aesKey = base64_decode($sessionKey);
    $aesIV = base64_decode($iv);
    $aesCipher = base64_decode($encryptedData);

    $result = openssl_decrypt($aesCipher, 'AES-128-CBC', $aesKey, OPENSSL_RAW_DATA, $aesIV);
    return json_decode($result, true);
  }
}
